import axios from "axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import { useRouter } from "vue-router";
import { login } from "@/utils/shuiwu/api";

//  baseURL地址需保持和代理地址一致  *********重要信息zhw  文件上传

// export const baseURL = `http://192.168.254.36:9000`
export const baseURL = `/`;
// 全局设置缓存头（对所有axios请求生效）--new
// axios.defaults.headers.common['Cache-Control'] = 'max-age=3600';
// 创建 axios 实例
const service = axios.create({
  baseURL, // 正式
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 请求拦截器
let loginPromise: Promise<string> | null = null;
service.interceptors.request.use(
  async (config: any) => {
    if (config.url === "/geo/v2/city/lookup?location=银川") {
      config.baseURL = "/";
      config.headers["X-QW-Api-Key"] = "efc5709adc0a453793cdabf5b94245fb";
    }
    if (config.url === "/v2.6/Y2FpeXVuX25vdGlmeQ==/101.6656,39.2072/daily") {
      config.baseURL = "/";
    }
    const parts = config.url.split("/");
    const result = parts[1];
    if (
      result === "api-9000" &&
      config.url !== "/api-9000/prod-api/auth/ssoLogin"
    ) {
      const token = localStorage.getItem("TOKEN");
      if (token) {
        config.headers["Authorization"] = `Bearer ${token}`;
      } else {
        if (!loginPromise) {
          loginPromise = login().then((res: any) => {
            localStorage.setItem("TOKEN", res.data);
            return res.data;
          });
        }
        const newToken = await loginPromise;
        config.headers["Authorization"] = `Bearer ${newToken}`;
      }
    }

    if (!config.headers) {
      throw new Error(
        `Expected 'config' and 'config.headers' not to be undefined`
      );
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (
      response.config.url ===
      "/v2.6/Y2FpeXVuX25vdGlmeQ==/101.6656,39.2072/daily"
    )
      return response.data;
    const { code, msg } = response.data;

    // return response.data
    if (code == "200" || code == "20005" || code == "20006" || code === 0) {
      return response.data;
    } else {
      if (code === 401) {
        console.log("token过期");
        
        // token 过期\
      }
      // 响应数据为二进制流处理(Excel导出)
      if (response.data instanceof ArrayBuffer) {
        return response;
      }

      return Promise.reject(new Error(msg || "Error"));
    }
  },
  (error: any) => {
    const { code, msg } = error.response.data;
    return Promise.reject(new Error(msg || "Error"));
  }
);

// 导出 axios 实例
export default service;
